/**
 * 
 */
package com.recruit.publicMail;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;







import java.util.Timer;

import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeUtility;

import org.apache.commons.mail.EmailAttachment;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;

import sun.misc.BASE64Decoder;

import com.eos.common.mail.MailFactory;
import com.eos.system.annotation.Bizlet;
import com.primeton.ext.infra.security.BASE64Encoder;

import commonj.sdo.DataObject;

/**
 * @author zengjunjie
 * @date 2018-09-19 11:22:00
 *
 */
@Bizlet("")
public class JointEmail {

	String files="";
	
	@Bizlet("文件加密")
	public static String encodeBase64File(String targetPath) throws Exception {
		
		String base64Code="";
		//输入流
		FileInputStream inputFile = null;
		
		String[] path=targetPath.split(",");
		
		for(int i=0;i<path.length;i++){
			
			File file = new File(path[i]);
			inputFile = new FileInputStream(file);
			byte[] buffer = new byte[(int) file.length()];
			inputFile.read(buffer);
			
			//加密成Base64格式
			String Base64Code= new BASE64Encoder().encode(buffer);
			base64Code+=Base64Code+",";
		}
		//删除最后一个字符
		base64Code = base64Code.substring(0,base64Code.length() - 1);
        inputFile.close();
        return base64Code;
 
    }
	
	@Bizlet("文件解密")
	/**
	 * base64码转换为文件流
	 * @param base64Code 加密结果
	 * @param targetPath	文件路径
	 * @param catalogue		存储路径
	 * @throws Exception
	 */
	public static Map decoderBase64File(String base64Code, String targetPath,String catalogue){
		
		String rum="成功";
		Map map=new HashMap();
		
		//定义接收文件名
		String fileName = null;
		String FileName = "";
		//定义接收存储路劲加文件名
		File absolutePath = null;
		String AbsolutePath="";
		//输出流
		FileOutputStream out = null;
		
		String[] base=base64Code.split(",");
		String[] path=targetPath.split(",");
		
		try {
		    File file = new File(catalogue);
		    //如果文件夹不存在,就新建一个
		    if(!file.exists()){
		    	file.mkdirs();
		    }
		    
		    for(int i=0;i<path.length;i++){
		    	
		    	File f =new File(path[i]);
		    	//获取文件名加后缀
		    	fileName=f.getName();
		    	
		    	absolutePath = new File(catalogue, fileName);
		    	//如果文件不存在,就新建一个
		    	if(!absolutePath.exists()){
		    		try {
		    			absolutePath.createNewFile();
		    		} catch (IOException e) {
		    			// TODO Auto-generated catch block
		    			e.printStackTrace();
		    		}
		    	}
		    	byte[] buffer = new BASE64Decoder().decodeBuffer(base[i]);
		    	out = new FileOutputStream(absolutePath);
		    	out.write(buffer);
		    	
		    	//拼接地址和名字
		    	FileName+=fileName+",";
		    	AbsolutePath+=absolutePath+",";
		    }
		    
		    //删除最后一个字符
		    FileName = FileName.substring(0,FileName.length()- 1);
			AbsolutePath = AbsolutePath.substring(0,AbsolutePath.length()- 1);
	       
			out.flush();
	        
	        
		} catch (Exception e) {
			rum="失败";
			
		}finally{
			 //关闭
	        try {
				out.close();
			} catch (IOException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}
		}
		
		map.put("rum", rum);
		map.put("file", AbsolutePath);
		map.put("fileName",FileName);
		
		return map;
	}
	
	@Bizlet("")
	//拼接hrml ：校招通关邀请
	public String jointHTML(String html) throws EmailException {
		//定义发送内容  HTML格式
		String html2="<html><body>";
		html2+=html;
		
		html2+="</body></html>";
		
		return html2;
	}
	
	/**
	 * 发送邮件
	 * @param smtp		服务器地址
	 * @param smtpProt	服务器号
	 * @param account	账号
	 * @param password	密码
	 * @param sender	发送人
	 * @param senderName	发送人名称
	 * @param to		收件人
	 * @param cc		抄送
	 * @param bcc		密送
	 * @param subject	主题
	 * @param html		内容
	 * @param file		附件
	 * @param fileName	附件名
	 * @return
	 */
	@Bizlet("发送邮箱")
	public String sendMail(String smtp,int smtpProt,String account,String password,String sender,String senderName,
							String to,String cc,String bcc,String subject,String html,
							String file,String fileName){
		
		HtmlEmail mail = MailFactory.getHtmlEmailInstance();
		
		
		//附件
		String[] File = {};
		if(file!="" && file!=null){
			File=file.split(",");
		}
				
		//附件名
		String[] FileName = {};
		if(fileName!="" && fileName!=null){
			FileName=fileName.split(",");
		}
		
		
		String obj = "发送成功";
		 
		try {
			
			//设置SMTP服务器地址
			mail.setHostName(smtp);
			//设置SMTP服务号
			mail.setSmtpPort(smtpProt);
			
			//如果需要用户验证，设定用户名和密码
			mail.setAuthentication(account, password);
			//设定发送者邮件地址
			//判断是否有名称
			if(senderName=="" || senderName==null){
				mail.setFrom(sender);
			}else{
				mail.setFrom(sender,senderName);
			}

			//设定收件人邮件地址
			String[] toMail = {};
			if(to!=null && to!=""){
				toMail = to.split(",");
				for(int i = 0 ;i<toMail.length;i++){
					mail.addTo(toMail[i]);
				}
				
			}
			
			//设定抄送人邮件地址
			String[] ccMail = {};
			if(cc!=null && cc!=""){
				ccMail = cc.split(",");
				for(int i = 0 ;i<ccMail.length;i++){
					mail.addCc(ccMail[i]);
				}
				
			}
			//设定密送人邮件地址
			String[] bccMail = {};
			if(bcc!=null && bcc!=""){
				bccMail = bcc.split(",");
				for(int i = 0 ;i<bccMail.length;i++){
					mail.addBcc(bccMail[i]);
				}

			}
			
			// 字符编码集的设置
			mail.setCharset("utf-8");
			
			//设定主题
			mail.setSubject(subject);
			//设定消息内容
			mail.setHtmlMsg(html);
			
			if(file!="" && file!=null){
				//循环附件
				for(int i=0;i<File.length;i++){
					
					//创建附件
					EmailAttachment attTxt = new EmailAttachment();
					//附件
					attTxt.setPath(File[i]);
					//附件名:MimeUtility.encodeText()防止中文乱码
					attTxt.setName(MimeUtility.encodeText(FileName[i]));
					
					mail.attach(attTxt);
				}
			}
			
			mail.send();
			
		} catch (Exception e) {
			obj="发送失败";
		}
		
		return obj;
		
	}
	/**
	 * 删除附件
	 * @param fullFilePath  附件绝对路径
	 * @return 
	 */
	@Bizlet("删除附件目录")
	public void deleteAllFiles(File fullFilePath) {
		
		File files[] = fullFilePath.listFiles();  
        if (files != null)  
            for (File f : files) {  
                if (f.isDirectory()) { // 判断是否为文件夹  
                    deleteAllFiles(f);  
                    try {  
                        f.delete();  
                        
                    } catch (Exception e) { 
                    	
                    }  
                } else {  
                    if (f.exists()) { // 判断是否存在  
                        deleteAllFiles(f);  
                        try {  
                            f.delete(); 
                            
                        } catch (Exception e) {  
                        	
                        }  
                    }  
                }  
            }
    }
	
	@Bizlet("字符串转换File")
	public Map stringTurnFile(String fullFilePath) {
		
		Map map=new HashMap();
		
		File file = new File(fullFilePath);
		
		map.put("file",file);
		
		return map;

    }
	
	/*public static void main(String[] args) {
		JointEmail t = new JointEmail();
		//deleteFile("D:/12334.png");
		try {
			String ret = t.encodeBase64File("D:/12334.png");
			System.err.println(ret);
			t.decoderBase64File(ret, "D:/12334.png", "E:/");
		} catch (Exception e) {
			// TODO Auto-generated catch block 
			e.printStackTrace();
		}
	}*/
}
